/**
 * JQuery前台验证框架.
 * 
 * JQuery-Framework-Validator PlugIn
 * 
 * @author 324945 AndyDai
 *   
 * CreateDate: 2012-5-9
 * 
 **/
if (typeof jQueryJEvent == "undefined") { var jQueryJEvent = new Object();}

jQueryJEvent.Event = function(name,capture,bubble,data,target){
	this.name    = name;
	this.capture = capture;
	this.bubble  = bubble;
	this.data    = data;
	this.target  = target;
};

jQueryJEvent.poolUnit = function(name,handleArray){
	this.name = name;
	if(handleArray instanceof Array){
		this.handleArray = handleArray;
	}else{
		this.handleArray = [handleArray];
	}
	
};

jQueryJEvent.handleUnit = function(jQueryObj,capture,bubble,func){
	this.jQueryObj = jQueryObj;
	this.capture   = capture;
	this.bubble    = bubble;
	this.func      = func;
};

jQueryJEvent.jEventController = function(){
	if(jQueryJEvent.jEventController.caller != jQueryJEvent.getJEventControllerInstance){
		throw new Error("非法调用jEventController的构造函数");return;
	}
	this.eventPool = [];
};

jQueryJEvent.jEventController.prototype = {
	handleJEvent: function(jEvent){		
		var parentArray1 = null;
		for(var i=0;i<this.eventPool.length;i+=1){
			if(this.eventPool[i].name == jEvent.name){
				if (jEvent.capture) {
					if(parentArray1 == null){parentArray1 = jQuery.getParentsArray(jEvent.target);}
					for(var m=parentArray1.length-1;m>=0;m-=1){
						var handleArray1 = parentArray1[m].getJEventListener(jEvent.name);
						for(var j=0;j<handleArray1.length;j+=1){
							if(handleArray1[j].capture){
								handleArray1[j].func.call(handleArray1[j].jQueryObj,jEvent.data,"capture");
							}
						}
					}
				}						
				if(jEvent.target.hasJEventListener(jEvent.name)){
					var handleArray2 = jEvent.target.getJEventListener(jEvent.name);
					for(var k=0;k<handleArray2.length;k+=1){
						handleArray2[k].func.call(handleArray2[k].jQueryObj,jEvent.data,"target");
					}
				}
				if(jEvent.bubble){
					if(parentArray1 == null){parentArray1 = jQuery.getParentsArray(jEvent.target);}
					for(var x=0;x<parentArray1.length;x+=1){
						var handleArray3 = parentArray1[x].getJEventListener(jEvent.name);
						for(var l=0;l<handleArray3.length;l+=1){
							if(handleArray3[l].bubble){
								handleArray3[l].func.call(handleArray3[l].jQueryObj,jEvent.data,"bubble");
							}
						}
					}
				}
			}
		}			
	},
	addjEventListener:function(jQueryObj,name,capture,bubble,func){
		for(var i=0;i<this.eventPool.length;i+=1){
			if(this.eventPool[i].name == name){
				this.eventPool[i].handleArray.push(new jQueryJEvent.handleUnit(jQueryObj,capture,bubble,func));
				return;							
			}
		}
		this.eventPool.push(new jQueryJEvent.poolUnit(name,new jQueryJEvent.handleUnit(jQueryObj,capture,bubble,func)));
	},
	removeEventListener:function(jQueryObj,name,func){
		for(var i=0;i<this.eventPool.length;i+=1){
			if(this.eventPool[i].name == name){
				for(var j=0;j<this.eventPool[i].handleArray.length;j+=1){
					if(this.eventPool[i].handleArray[j].jQueryObj[0] == jQueryObj[0] && this.eventPool[i].handleArray[j].func == func){
						this.eventPool[i].handleArray.splice(j,1);
						return;
					}
				}
			}
		}		
	},
	hasJEventListener:function(jQueryObj,name){
		for(var i=0;i<this.eventPool.length;i+=1){
			if(this.eventPool[i].name == name){
				for(var j=0;j<this.eventPool[i].handleArray.length;j+=1){
					if(this.eventPool[i].handleArray[j].jQueryObj[0] == jQueryObj[0]){
						return true;
					}
				}
			}
		}
		return false;
	},
	getJEventListener:function(jQueryObj,name){
		var handleArrayRet = [];
		for(var i=0;i<this.eventPool.length;i+=1){
			if(this.eventPool[i].name == name){				
				for(var j=0;j<this.eventPool[i].handleArray.length;j+=1){
					if(this.eventPool[i].handleArray[j].jQueryObj[0] == jQueryObj[0]){
						handleArrayRet.push(this.eventPool[i].handleArray[j]);
					}
				}
			}
		}
		return handleArrayRet;
	}
};
jQueryJEvent.singleJEventController = null;
jQueryJEvent.getJEventControllerInstance = function(){
	if(jQueryJEvent.singleJEventController == null){
		jQueryJEvent.singleJEventController = new jQueryJEvent.jEventController();
	}
	return jQueryJEvent.singleJEventController;
};

$.fn.extend({
	dispatchJEvent: function(name/*string*/,data,capture,bubble){		
		capture = capture || true;//发出事件时默认开启捕获
		bubble  = bubble  || true;//发出事件时默认开启冒泡
		var controller = jQueryJEvent.getJEventControllerInstance();
		var jEvent = jQuery.createJEvent(name,capture,bubble,data,this);
		controller.handleJEvent(jEvent);
	},
	addJEventListener:function(name,func,capture,bubble){		
		capture = capture || false;//添加监听时默认不开启捕获
		bubble  = bubble  || true; //添加监听时默认开启冒泡
		var controller = jQueryJEvent.getJEventControllerInstance();
		controller.addjEventListener(this,name,capture,bubble,func);	
	},
	removeJEventListener:function(name,func){
		var controller = jQueryJEvent.getJEventControllerInstance();
		controller.removeEventListener(this,name,func);
	},
	hasJEventListener:function(name){
		var controller = jQueryJEvent.getJEventControllerInstance();	
		return	controller.hasJEventListener(this,name);
	},
	getJEventListener:function(name){
		var controller = jQueryJEvent.getJEventControllerInstance();	
		return controller.getJEventListener(this,name);
	}
});

$.extend({
	createJEvent:function(name,capture,bubble,data,target){
		return new jQueryJEvent.Event(name,capture,bubble,data,target);
	},
	getParentsArray:function(jQueryObj){
		var parentsArray = [];
		if(jQueryObj[0] == jQuery(document)[0]){return parentsArray;}
		var tempParent = null;		
		for(tempParent = jQueryObj.parent();tempParent[0]!=jQuery(document)[0];tempParent=tempParent.parent()){			
			parentsArray.push(tempParent);
		}
		parentsArray.push(jQuery(document));
		return parentsArray;
	},
	checkInArray:function(ele,array,isJQuery){
		isJQuery = isJQuery || true;
		for(var i=0;i<array.length;i+=1){
			if(isJQuery){
				if(array[i][0] == ele[0]){
					return true;
				}
			}else{
				if(array[i] == ele){
					return true;
				}
			}
		}
		return false;
	}
});

var $jqueryValidError = 0;	//错误计数.
var $jqueryValidGroupErrorArray = []; //分组错误数组.
var ReloadMap = {};	//是否重新加载验证框架
var CallBackMap = {};	//回调函数Map

/**
 * 验证字符最小长度
 *
 */
this.minWordLength = function($value,$byteLength){
	var $newValue = $value;
	var $length = $newValue.length;
	
	if(parseInt($length,10) >= parseInt($byteLength,10)){
		return true;
	}
	else{
		return false;
	}
};

/**
 * 验证字符最大长度
 *
 */
this.maxWordLength = function($value,$byteLength){
	var $newValue = $value;
	var $length = $newValue.length;
	
	if(parseInt($length,10) <= parseInt($byteLength,10)){
		return true;
	}
	else{
		return false;
	}
};

/**
 * 验证字符最小长度-支持中文
 *
 */
this.minLength = function($value,$byteLength){
	var $newValue = $value.replace(/[^\x00-\xff]/g,"**");
	var $length = $newValue.length;
	
	if(parseInt($length,10) >= parseInt($byteLength,10)){
		return true;
	}
	else{
		return false;
	}
};

/**
 * 验证字符最大长度-支持中文
 *
 */
this.maxLength = function($value,$byteLength){
	var $newValue = $value.replace(/[^\x00-\xff]/g,"**");
	var $length = $newValue.length;
	
	if(parseInt($length,10) <= parseInt($byteLength,10)){
		return true;
	}
	else{
		return false;
	}
};

/**
 * 验证字符最大长度-支持中文 一个汉字3个字符
 *
 */
this.maxLengthChina = function($value,$byteLength){
	var $newValue = $value.replace(/[^\x00-\xff]/g,"***");
	var $length = $newValue.length;
	
	if(parseInt($length,10) <= parseInt($byteLength,10)){
		return true;
	}
	else{
		return false;
	}
};

/**
 * 验证处理函数.
 */
$.validateFun = function(data){
	var $target = $("#"+data.tarId);
	
	//没有找到目标即返回
	if($target.size() == 0){
		return;
	}
	
	//是否隐藏时进行验证.
	if(!data.validInHidden && $target.is(":hidden")){
		return;
	}
	
	//禁用时是否验证.
	if(!data.validInDisabled && $target.is(":disabled")){
		return;
	}
	
	data.errorMsg = undefined;
	data.successMsg = undefined;
	
	//为空验证.
	if(data.required != undefined && data.required == true){
		if($.trim($target.val()) == ""){
			data.errorMsg = data.label+"不能为空!";
			$.showMsg(data);
			return;
		}
	}
	
	//电话号码验证.
	if(data.txtType != undefined && data.txtType == "phone"){
		if($.trim($target.val()) != "" && (!/^(\([0-9]{3,4}\)|[0-9]{3,4}-|\s)?[0-9]{7,14}$/.test($.trim($target.val())))){
			data.errorMsg = data.label+"不是有效的号码格式!";
			$.showMsg(data);
			return;
		}
	}
	
	//手机号码验证.
	if(data.txtType != undefined && data.txtType == "mobile"){
		if($.trim($target.val()) != "" && (!/^(((13[0-9]{1})|130|131|132|133|134|135|136|137|138|139|150|151|152|153|155|156|157|158|159|180|182|185|186|187|188|189)+\d{8})$/.test($.trim($target.val())))){
			data.errorMsg = data.label+"不是有效的号码格式!";
			$.showMsg(data);
			return;
		}
	}
	
	//座机号码验证.
	if(data.txtType != undefined && data.txtType == "tel"){
		if($.trim($target.val()) != "" && (!/^(\d){3,4}-(\d){6,8}$/.test($.trim($target.val())))){
			data.errorMsg = data.label+"不是有效的号码格式!";
			$.showMsg(data);
			return;
		}
	}
	
	//电子邮件验证.
	if(data.txtType != undefined && data.txtType == "email"){
		if($.trim($target.val()) != "" && !/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"不是有效的电子邮箱格式!";
			$.showMsg(data);
			return;
		}
	}
	
	//顺丰电子邮件验证.
	if(data.txtType != undefined && data.txtType == "xn-email"){
		if($.trim($target.val()) != "" && !/\w+([-+.]\w+)*@xiaoniu66.com$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"不是有效的小牛资本邮箱格式!";
			$.showMsg(data);
			return;
		}
	}
	
	//网址验证.
	if(data.txtType != undefined && data.txtType == "url"){
		var strRegex = "^((https|http|ftp|rtsp|mms)?://)"  
  		+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@  
        + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184  
        + "|" // 允许IP和DOMAIN（域名） 
        + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.  
        + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名  
        + "[a-z]{2,6})" // first level domain- .com or .museum  
        + "(:[0-9]{1,4})?" // 端口- :80  
        + "((/?)|" // a slash isn't required if there is no file name  
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
		if($.trim($target.val()) != "" && !(new RegExp(strRegex)).test($.trim($target.val()))){
			data.errorMsg = data.label+"不是有效的网址格式!";
			$.showMsg(data);
			return;
		}
	}
	
	//ip验证.
	if(data.txtType != undefined && data.txtType == "ip"){
		if($.trim($target.val()) != "" && !/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"不是有效的IP格式!";
			$.showMsg(data);
			return;
		}
	}
	
	//身份证验证.
	if(data.txtType != undefined && data.txtType == "id"){
		if($.trim($target.val()) != "" && !/^((11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65|71|81|82|91)\d{4})((((19|20)(([02468][048])|([13579][26]))0229))|((20[0-9][0-9])|(19[0-9][0-9]))((((0[1-9])|(1[0-2]))((0[1-9])|(1\d)|(2[0-8])))|((((0[1,3-9])|(1[0-2]))(29|30))|(((0[13578])|(1[02]))31))))((\d{3}(x|X))|(\d{4}))$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"不是有效的身份证格式!";
			$.showMsg(data);
			return;
		}
	}
	
	//中国邮政编码验证.
	if(data.txtType != undefined && data.txtType == "postCode"){
		if($.trim($target.val()) != "" && !/^[1-9]{1}(\d){5}$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"不是有效的邮政编码格式!";
			$.showMsg(data);
			return;
		}
	}
	
	//字符长度验证.
	if(data.minLength != undefined && $.trim(data.minLength.toString()) != ""){
		if(data.maxLength != undefined && $.trim(data.maxLength.toString()) != ""){
			if(data.maxLength == data.minLength){
				if($.trim($target.val()) != "" && getStrLength($target.val()) != data.minLength){
					data.errorMsg = data.label+"的长度必须等于"+data.minLength+"个字符!";
					$.showMsg(data);
					return;
				}
			}
		}
	}
	
	if(data.minLength != undefined && $.trim(data.minLength.toString()) != ""){
		if($.trim($target.val()) != "" && !minLength($target.val(),data.minLength)){
			data.errorMsg = data.label+"的长度必须大于等于"+data.minLength+"个字符!";
			$.showMsg(data);
			return;
		}
	}
	
	if(data.maxLength != undefined && $.trim(data.maxLength.toString()) != ""){
		if($.trim($target.val()) != "" && !maxLength($target.val(),data.maxLength)){
			data.errorMsg = data.label+"的长度必须小于等于"+data.maxLength+"个字符!";
			$.showMsg(data);
			return;
		}
	}
	//一个汉字3个字符的长度检验
	if(data.maxLengthChina != undefined && $.trim(data.maxLengthChina.toString()) != ""){
		if($.trim($target.val()) != "" && !maxLengthChina($target.val(),data.maxLengthChina)){
			data.errorMsg = data.label+"的长度必须小于等于"+data.maxLengthChina+"个字符!";
			$.showMsg(data);
			return;
		}
	}
	
	
	//字长度验证.
	if(data.minWordLength != undefined && $.trim(data.minWordLength.toString()) != ""){
		if(data.maxWordLength != undefined && $.trim(data.maxWordLength.toString()) != ""){
			if(data.maxWordLength == data.minWordLength){
				if($.trim($target.val()) != "" && $target.val().length != data.minWordLength){
					data.errorMsg = data.label+"的长度必须等于"+data.minWordLength+"!";
					$.showMsg(data);
					return;
				}
			}
		}
	}
	
	if(data.minWordLength != undefined && $.trim(data.minWordLength.toString()) != ""){
		if($.trim($target.val()) != "" && !minWordLength($target.val(),data.minWordLength)){
			data.errorMsg = data.label+"的长度必须大于等于"+data.minWordLength+"!";
			$.showMsg(data);
			return;
		}
	}
	
	if(data.maxWordLength != undefined && $.trim(data.maxWordLength.toString()) != ""){
		if($.trim($target.val()) != "" && !maxWordLength($target.val(),data.maxWordLength)){
			data.errorMsg = data.label+"的长度必须小于等于"+data.maxWordLength+"!";
			$.showMsg(data);
			return;
		}
	}
	
	//数字验证(全数字).
	if(data.isDigit != undefined && data.isDigit == true){
		if($.trim($target.val()) != "" && !/^([0-9]*)$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是数字!";
			$.showMsg(data);
			return;
		}
	}
	
	//验证是否为数字或大小写字母.
	if(data.isDigitOrLetter != undefined && data.isDigitOrLetter == true){
		if($.trim($target.val()) != "" && !/^([0-9a-zA-Z]*)$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是数字或大小写字母!";
			$.showMsg(data);
			return;
		}
	}
	
	//验证是否为合法企业证照号.
	if(data.isEpCertNo != undefined && data.isEpCertNo == true){
		if($.trim($target.val()) != "" && !/^([0-9a-zA-Z-]*)$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是数字或大小写字母或英文-!";
			$.showMsg(data);
			return;
		}
	}
	
	//验证是否为整数或小数.
	if(data.isDecimal != undefined && data.isDecimal == true){
		if($.trim($target.val()) != "" && !/^\d*(\.\d+)?$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是小数或整数";
			$.showMsg(data);
			return;
		}
	}
	
	// 验证是否为整数或小数（小数位最多为两位）
	if(data.isDecimalTo != undefined && data.isDecimalTo == true){
		if($.trim($target.val()) != "" && !/^\d*(\.\d{1,2})?$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是整数或精度不大于2的小数";
			$.showMsg(data);
			return;
		}
	}
	
	// 验证是否为整数或小数（小数位最多为四位）
	if(data.isDecimalFour != undefined && data.isDecimalFour == true){
		if($.trim($target.val()) != "" && !/^\d*(\.\d{1,4})?$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是整数或精度不大于4的小数";
			$.showMsg(data);
			return;
		}
	}
	
	//验证是否为金额  /^(([1-9][0-9]*)|([0]))(\.\d{1,2})$/   /^((\d{1,3}(\d{3})*)|(\d+))(\.\d{1,2})?$/
	if(data.isMoney != undefined && data.isMoney == true){
		if($.trim($target.val()) != "" && ! /^((([1-9][0-9]*)(\.\d{1,2})?)|([0])(\.(\d{1,2})))$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是合法的金额!";
			$.showMsg(data);
			return;
		}
	}
	
	//工本费校验，可以输入0,0.0,0.00
	if(data.flatCost != undefined && data.flatCost == true){
		var fc = $.trim($target.val());
		if( fc != "" && ! /^((([1-9]\d*)(\.\d{1,2})?)|([0])|([0])\.0{1,2}|([0])(\.([1-9][0-9]|[0][1-9])))$/.test(fc))
		{
			data.errorMsg = data.label+"必须是合法的金额!";
			$.showMsg(data);
			return;
		}
		if(fc > 1000){
			data.errorMsg = data.label+"不能大于1000!";
			$.showMsg(data);
			return;
		}
	}
	
	//充值金额校验，可以输入0,0.0,0.00，有效数字不大于5000
	if(data.recharge != undefined && data.recharge == true){
		var fc = $.trim($target.val());
		if( fc != "" && ! /^((([1-9]\d*)(\.\d{1,2})?)|([0])|([0])\.0{1,2}|([0])(\.([1-9][0-9]|[0][1-9])))$/.test(fc))
		{
			data.errorMsg = data.label+"必须是合法的金额!";
			$.showMsg(data);
			return;
		}
		if(fc > 5000){
			data.errorMsg = data.label+"不能大于5000";
			$.showMsg(data);
			return;
		}
	}
	
	//退款金额校验，可以输入0,0.0,0.00
	if(data.returnAmt != undefined && data.returnAmt == true){
		var fc = $.trim($target.val());
		if( fc != "" && ! /^((([0-9]\d*)(\.\d{1,2})?)|([0])|([0])\.0{1,2}|([0])(\.([1-9][0-9]|[0][1-9])))$/.test(fc))
		{
			data.errorMsg = data.label+"必须是合法的!";
			$.showMsg(data);
			return;
		}
	}
	
	// 判断输入是否是有效的长日期格式 - "YYYY-MM-DD HH:MM:SS" || "YYYY/MM/DD HH:MM:SS"
	if(data.isLDate != undefined && data.isLDate == true){
		if($.trim($target.val()) != "" && !/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"不是有效的YYYY-MM-DD HH:MM:SS || YYYY/MM/DD HH:MM:SS日期格式!";
			$.showMsg(data);
			return;
		}
	}
	
	// 检查是否为 YYYY-MM-DD || YYYY/MM/DD 的日期格式
	if(data.isSDate != undefined && data.isSDate == true){
		if($.trim($target.val()) != "" && !/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2})$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"不是有效的YYYY-MM-DD || YYYY/MM/DD日期格式!";
			$.showMsg(data);
			return;
		}
	}
	
	//验证包含空格
	if(data.isBLANK != undefined && data.isBLANK == true){
		if($target.val() != "" && !($target.val().indexOf(' ')==-1)){
			data.errorMsg = data.label+"不能含有空格!";
			$.showMsg(data);
			return;
		}
	}
	
	//验证非零的正整数
	
	if(data.isNZADigit != undefined && data.isNZADigit == true){
		if($.trim($target.val()) != "" && !/^\+?[1-9][0-9]*$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是非零正整数!";
			$.showMsg(data);
			return;
		}
	}
	
	//验证非负整数
	if(data.isADigit != undefined && data.isADigit == true){
		if($.trim($target.val()) != "" && !/^\d+$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是非负整数!";
			$.showMsg(data);
			return;
		}
	}
	
	//验证非零的负整数
	if(data.isNZNDigit != undefined && data.isNZNDigit == true){
		if($.trim($target.val()) != "" && !/^\-[1-9][0-9]*$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是非零正整数!";
			$.showMsg(data);
			return;
		}
	}
	
	//验证非正整数
	if(data.isNDigit != undefined && data.isNDigit == true){
		if($.trim($target.val()) != "" && !/^((-\d+)|(0+))$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是非正整数!";
			$.showMsg(data);
			return;
		}
	}
	
	//中文验证.
	if(data.isChinese != undefined && data.isChinese == true){
		if($.trim($target.val()) != "" && !/^[\u4e00-\u9fa5]+$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是中文!";
			$.showMsg(data);
			return;
		}
	}
	//中文或英文字母验证.
	if(data.isChinOrEng != undefined && data.isChinOrEng == true){
		if($.trim($target.val()) != "" && !/^[\u4e00-\u9fa5a-zA-Z]+$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"必须是中文或英文字母!";
			$.showMsg(data);
			return;
		}
	}
	
	//非中文验证.
	if(data.isNotChinese != undefined && data.isNotChinese == true){
		if($.trim($target.val()) != "" && /[\u4e00-\u9fa5]/.test($.trim($target.val()))){
			data.errorMsg = data.label+"不能为中文!";
			$.showMsg(data);
			return;
		}
	}
	
	//不能是纯数字验证
	if(data.isNotAllDigit != undefined && data.isNotAllDigit == true){
		if($.trim($target.val()) != "" && /^[0-9]+$/.test($.trim($target.val()))){
			data.errorMsg = data.label+"不能为纯数字";
			$.showMsg(data);
			return;
		}
	}
	
	//验证file域文件大小(单位:字节)--建议后台验证ie7+不支持..
	if(data.fileMaxSize != undefined && $.trim(data.fileMaxSize.toString()) != ""){
		if($.trim($target.val()) != "" && $.trim($target.attr("type").toString().toLowerCase()) === "file"){
			var $tar = document.getElementById(data.tarId);
			var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
			
			var filesize = 0;
			if(isIE && !$tar.files){
				var filePath = $.trim($target.val());
				var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
				var file = fileSystem.GetFile(filePath);       
				filesize = file.Size;
			}
			else{
				filesize = $tar.files[0].size;
			}

			if(filesize > parseInt(data.fileMaxSize,10)){
				var _fileSize = parseInt(data.fileMaxSize,10) / parseFloat(1024);
				data.errorMsg = data.label+"的文件大小必须小于等于"+_fileSize+"KB!";
				$.showMsg(data);
				return;
			}
		}
	}
	
	//验证file域文件类型.
	if(data.fileType != undefined && $.trim(data.fileType.toString()) != ""){
		if($.trim($target.val()) != ""){
			var $filePath = $.trim($target.val());
			var $ext = $filePath.substring($filePath.lastIndexOf('.')+1).toLowerCase();
			if($.trim(data.fileType.toString()).toString().indexOf($ext) == -1){
				data.errorMsg = data.label+"的文件类型必须为"+data.fileType+"!";
				$.showMsg(data);
				return;
			}
		}
	}
	
	//图像像素大小验证--建议后台验证firefox,ie7+不支持..
	if(data.imgPix != undefined && $.trim(data.imgPix.toString()) != ""){
		if($.trim($target.val()) != "" && $.trim($target.attr("type").toString().toLowerCase()) == "file"){
			var $imgPix = $.trim(data.imgPix.toString());
			var $width 	= parseInt($imgPix.substring(0,$imgPix.indexOf("*")));
			var $height	= parseInt($imgPix.substring($imgPix.indexOf("*")+1));
			var $imgFile = {};
			
			if(navigator.userAgent.toLowerCase().indexOf("msie") != -1){
				var $file = new Image();
				$file.src = $.trim($target.val());
				$imgFile.width = $file.width;
				$imgFile.height= $file.height;
			}
			
			if($imgFile.width != $width || $imgFile.height != $height){
				data.errorMsg = data.label+"的像素大小必须为"+data.imgPix+"!";
				$.showMsg(data);
				return;
			}
		}
	}
	
	//自定义函数验证.
	if(data.customFun != undefined && $.trim(data.customFun.toString()) != ""){
		var funStr = data.customFun.toString();
		var fun = funStr.substr(0,funStr.indexOf("["));
		var params = undefined;
		var rs = undefined;
		
		if($.trim(funStr) == ""){
			return;
		}

		if(fun != undefined && $.trim(fun) == ""){
			fun = funStr;
		}
		else{
			params = (funStr.substring(parseInt(funStr.indexOf("["))+1,parseInt(funStr.indexOf("]"))).split(","));
		}
		
		if(typeof(eval(fun)) != "function"){
			throw new Error("不是有效的Javascript函数.");
			return;
		}
		
		if(params != undefined){
			var param = "";
			for(var i=0;i<params.length;i++){
				param += "\""+params[i]+"\",";
			}
			params = param.substring(0,param.length-1);
		}
		
		try{
			params == undefined?rs = eval(fun+"()"):rs = eval(fun+"("+params+")");
			if(rs.result != undefined && rs.msg != undefined){
				if(rs.result == false){
					data.errorMsg = $.trim(rs.msg.toString())+"!";
					$.showMsg(data);
					return;
				}
				else if(rs.result == true){
					data.successMsg = $.trim(rs.msg.toString())+"!";
					$.showMsg(data);
					return;
				}
			}
		}
		catch(e){
			data.errorMsg = e.message+"!";
			$.showMsg(data);
			return;
		}
	}
};

/**
 * 重置处理函数.
 */
$.resetFun = function(data){
	var $target = $("#"+data.tarId);
	
	//没有找到目标即返回
	if($target.size() == 0){
		return;
	}
	
	if(data.needReset == false){
		return;
	}
	
	if(data.isDisabledNeedReset == false && $target.is(":disabled")){
		return;
	}
	
	if(data.isHiddenNeedReset == false && $target.is(":hidden")){
		return;
	}
	
	//如果重置类型是还原旧值.则执行还原操作.
	if($.trim(data.resetType) == "recovery"){
		var $value = $target.attr("validOldValue");
		
		if($target.get(0).tagName.toLowerCase() == "select"){
			$target.val($value);
		}
		else if($target.get(0).tagName.toLowerCase() == "input" && $.trim($target.attr("type")) == "file"){
			$target.after($target.clone().val($value));   
			$target.remove();
		}
		else{
			$target.val($value);
		}
		return;
	}
	
	if($target.get(0).tagName.toLowerCase() == "select"){
		$target[0].selectedIndex = 0;
	}
	else if($target.get(0).tagName.toLowerCase() == "input" && $.trim($target.attr("type")) == "file"){
		$target.after($target.clone().val(""));   
		$target.remove();
	}
	else{
		$target.val("");
	}
};

/**
 * 显示提交提示.
 * 
 * @param $guid
 * @param type
 * @param msg
 */
this.showOnSubmitTip = function($guid,type,msg){
	var $loadingMsg = $("#"+$guid+"_loading_msg");
	
	if(type == "normal"){
		$loadingMsg.empty().html(msg).show();//显示操作提示.
	}
	else if(type == "artDialog"){
		art.dialog({
			id:"loadingDialog",
			title:"Loading",
			content:msg,
			init:function(){
				$(".aui_title").each(function(){
					var $target = $(this);
					if($.trim($target.text()) == "Loading"){
						$target.parent().hide();
					}
				});
			},
			close:function(){
				$(".aui_title").each(function(){
					var $target = $(this);
					if($.trim($target.text()) == "Loading"){
						$target.parent().show();
					}
				});
			},
			esc:false,
			lock:true
		});
	}
	else if(type == "divDialog"){
		$loadingMsg.attr("class","jy_layer").show();
	}
};

/**
 * 显示提交后提示.
 * 
 * @param $guid
 * @param type
 * @param msg
 * @returns
 */
this.showAfterSubmitTip = function($guid,type){
	var $loadingMsg = $("#"+$guid+"_loading_msg");
	
	if(type == "normal"){
		$loadingMsg.fadeOut("fast",function(){	//隐藏操作提示.
		});
	}
	else if(type == "artDialog"){
		art.dialog({id:'loadingDialog'}).close();
	}
	else if(type == "divDialog"){
		$loadingMsg.hide();
	}
};

/**
 * 显示结果处理函数.
 */
$.showMsg = function(datas){
	var data = $.extend({},datas);
	//存在groupId的控件，错误提示集中显示在最后一个控件后面.
	if(data.groupId != undefined && $.trim(data.groupId.toString()) != ""){
		if($.inArray(data.groupId,$jqueryValidGroupErrorArray) != -1){
			return;
		}
		
		var $lastGroupComp = data.container.find("*[validGroupId='"+$.trim(data.container.attr("id")+"_"+data.groupId.toString())+"']").last();
		data.tarId = $lastGroupComp.attr("id");
	}
	
	var $msgTip = $("#"+data.tarId+"_msg_tip");
	
	if($.trim(data.errorMsg) == "" && $.trim(data.successMsg) == ""){return;}
	
	if(data.errorMsg != undefined && $.trim(data.errorMsg.toString()) != ""){
		$jqueryValidError++;	//错误计数加1.
		
		if(data.groupId != undefined && $.trim(data.groupId.toString()) != ""){
			$jqueryValidGroupErrorArray.push(data.groupId);
		}
		data.styleClass = data.errorStyle;
		data.tipMsg = data.errorMsg;
	}
	else if(data.successMsg != undefined && $.trim(data.successMsg.toString()) != ""){
		data.styleClass = data.successStyle;
		data.tipMsg = data.successMsg;
	}
	
	
	if($msgTip.size() == 0){
		
		if($("#"+data.tarId+"_required").size() == 0){
			//紧跟控件后的文字.
			if(data.suffixTxt != undefined && $.trim(data.suffixTxt) != ""){
				$("#"+data.tarId).after(data.suffixTxt+"<span class='"+data.styleClass+"' style='display:none;' id='"+data.tarId+"_msg_tip'>"+data.tipMsg+"</span>");
			}
			//紧跟控件后的HTML块.
			else if(data.suffixTagId != undefined && $.trim(data.suffixTagId) != ""){
				var _tarId = document.getElementById(data.suffixTagId);
				$("#"+data.suffixTagId).remove();
				$("#"+data.tarId).after(_tarId.outerHTML+"<span class='"+data.styleClass+"' style='display:none;' id='"+data.tarId+"_msg_tip'>"+data.tipMsg+"</span>");
			}
			else{
				$("#"+data.tarId).after("<span class='"+data.styleClass+"' style='display:none;' id='"+data.tarId+"_msg_tip'>"+data.tipMsg+"</span>");
			}
		}
		else if($("#"+data.tarId+"_required").size() == 1){
			$("#"+data.tarId+"_required").after("<span class='"+data.styleClass+"' style='display:none;' id='"+data.tarId+"_msg_tip'>"+data.tipMsg+"</span>");
		}
		
		if(data.showSpeed != "none"){
			$("#"+data.tarId+"_msg_tip").fadeIn(data.showSpeed);
		}
		else{
			$("#"+data.tarId+"_msg_tip").show();
		}
	}
	else{
		if(data.showSpeed != "none"){
			$msgTip.attr("class",data.styleClass).text(data.tipMsg).fadeIn(data.showSpeed);
		}
		else{
			$msgTip.attr("class",data.styleClass).text(data.tipMsg).show();
		}
	}
};

(function($){
	
	//对象拓展.
	$.fn.validator = function(options,callbackFun){
		var $container 	= $(this),$guid = null;	//容器引用.
		
		//默认值.
		if(!options){options = {};}

		options = $.extend({
			required:true,					//不能为空.
			
			txtType:"text",					//组件类型.text:文本,phone:电话号码,email:电子邮件,url:网址,ip:ip地址.

			isOnBlurEnable:true,			//启用失去焦点验证.
			validInHidden:false,			//隐藏时是否验证.
			validInDisabled:false,			//禁用时是否验证.
			disabledFormSubmit:true,		//禁用表单提交.
			
			errorStyle:"frame_error",		//错误tip样式.
			successStyle:"frame_success",	//正确tip样式.
			requiredStyle:"error",			//必填项样式.
			requiredHTML:"*",				//必填项HTML样式.
	
			isRequiredStyleInUse:true,		//是否需要必填项样式.
			needReset:true,					//是否重置组件.
			resetType:"clean",				//重置类型.默认clean[清空]，recovery[还原成原来的值].
			isDisabledNeedReset:false,		//是否重置disabled组件.
			isHiddenNeedReset:false,		//是否重置隐藏组件.
			showFeildOnSubmit:false,		//是否在提交时隐藏表单.
			isLoadingColseOnHand:false,		//是否手动关闭Loading界面.
			showOnSubmitTip:true,
			
			submitTipType:"artDialog",		//提交Loading提示类型.默认"normal";"artDailog";"divDailog"
			showSpeed:"fast"				//错误显示速度 slow,normal,fast,none
		},options);

		if($container.attr("id")){
			$guid = $container.attr("id");	//容器标识.
		}
		else{
			throw new Error("Container missing id attribute or id is empty,please check!");
			return;
		}
		
		if(!ReloadMap[$guid]){
			ReloadMap[$guid] = false;
		}
		else{
			ReloadMap[$guid] = true;
		}
		
		//添加容器级加载显示
		if($("#"+$guid+"_loading_msg").size() == 0 && ReloadMap[$guid] == false){
			$container.before("<div id='"+$guid+"_loading_msg'></div>");
			isReload = true;	//设置验证框架重新加载标识为True
		}
		
		//屏蔽表单提交
		if(options.disabledFormSubmit == true && $container.get(0).tagName.toLowerCase() == "form" && ReloadMap[$guid] == false){
			$container.submit(function(){
				return false;
			});
		};
		
		//存在iframe加载，添加iframe完成加载事件，在iframe完成加载时关闭加载提示.
		if(options.iframeId != undefined && $.trim(options.iframeId) != "" && ReloadMap[$guid] == false){
			var iframe = document.getElementById($.trim(options.iframeId).toString());
			    
			if(iframe.attachEvent){   //For IE
			    iframe.attachEvent("onload",function(){
			    	if($.trim(iframe.src) != ""){
			    		showAfterSubmitTip($guid,options.submitTipType);
			    	}
			    });   
			}
			else{   //For FireFox
			    iframe.onload = function(){
			    	if($.trim(iframe.src) != ""){
			    		showAfterSubmitTip($guid,options.submitTipType);
			      	}
			    };   
			}
		}
		
		//检索所有需要验证的组件，并进行事件监听注册.
		var $valideComponent = "input[validator],select[validator],textarea[validator]";
		
		$container.find($valideComponent).each(function(){
			var $target 	= $(this);
			var $validate 	= $.trim($target.attr("validator"));
			var $myValidate = $.trim($target.attr("checkName"));
			var $tarId 		= "";
			var $data 		= {};
			var $afterDom   = "";
			
			if($myValidate){
				if(typeof validate === "object"){
					$validate = validate.config.getConfig($myValidate);
					$afterDom = $validate["afterDom"];
				}else{
					throw new Error("sf validate config error!");
					return;
				}
				
			}
			
			if($target.attr("id")){
				$tarId = $target.attr("id");
			}
			else{
				throw new Error("Component missing id attribute or id is empty,please check!");
				return;
			}
			
			var $options = $.extend({},options);					
			if($validate != "" && typeof $validate === "string"){
				$data = $.parseJSON($validate);
			}else if(typeof $validate === "object"){
				$data = $validate;
			}
			
			if(!$myValidate){
				$afterDom = $data["afterDom"];
			}
			
			$.extend($options,$data,{"container":$container});
			
			//分组.
			if($options.groupId != undefined && $.trim($options.groupId) != "" && typeof($target.attr("validGroupId")) == "undefined"){
				$target.attr("validGroupId",$.trim($guid+"_"+$options.groupId));
			}
			
			//判断重置类型，缓存旧值.
			if($.trim($options.resetType) == "recovery" && typeof($target.attr("validOldValue")) == "undefined"){
				$target.attr("validOldValue",$target.val());
			}
			
			if($options.isRequiredStyleInUse == true){
				if($options.required == true){
					var html = "";
					//紧跟控件后的文字.
					if($options.suffixTxt != undefined && $.trim($options.suffixTxt) != ""){
						if($("#"+$tarId+'_suffixTxt').size() == 0){
							html += "<span id='"+$tarId+"_suffixTxt'>"+$options.suffixTxt+"</span>";
						}
					}
					
					//紧跟控件后的HTML块.
					if($options.suffixTagId != undefined && $.trim($options.suffixTagId) != ""){
						var _tarId = document.getElementById($options.suffixTagId);
						$("#"+$options.suffixTagId).remove();
						html += _tarId.outerHTML;
					}
					
					//if(!$target.is(":hidden"))
					if($("#"+$tarId+'_required').size() == 0){
						html += "<span class='"+$options.requiredStyle+"' id='"+$tarId+"_required'>"+$options.requiredHTML+"</span>";
					}
					
					if($afterDom && $($afterDom).length !== 0){
						$($afterDom).after(html);
					}else{
						$target.after(html);
					}
				}
			}
			else{
				var html = "";
				//紧跟控件后的文字.
				if($options.suffixTxt != undefined && $.trim($options.suffixTxt) != ""){
					if($("#"+$tarId+'_suffixTxt').size() == 0){
						html += "<span id='"+$tarId+"_suffixTxt'>"+$options.suffixTxt+"</span>";
					}
				}
				
				//紧跟控件后的HTML块.
				if($options.suffixTagId != undefined && $.trim($options.suffixTagId) != ""){
					var _tarId = document.getElementById($options.suffixTagId);
					$("#"+$options.suffixTagId).remove();
					html += _tarId.outerHTML;
				}
				
				$target.after(html);
			}
			
			if($validate != ""){
				
				if(typeof($target.attr($tarId+"has_validate_event")) == "undefined"){
					//注册组件的验证事件,监听冒泡事件.
					$container.addJEventListener($guid+"_validate_event",function(data,state){
						
						$target.attr($tarId+"has_validate_event","Yes");	//防止重复事件注册
						
						//如果是失去焦点派发的验证事件，并且事件监听组件不是事件发起组件则返回.
						if(data.onBlurId != undefined && $.trim(data.onBlurId) != $.trim($tarId)){
							return;
						}
						else if(data.onBlurId != undefined){
							if($("span[id$='"+$tarId+"_msg_tip']").size() == 1){
								$("span[id$='"+$tarId+"_msg_tip']").hide();
							}	
						}
						
						$.extend($options,{"tarId":$tarId},data);
		
						if(data.type == "submit"){
							$.validateFun($options);
						}
						else if(data.type == "reset"){
							$.resetFun($options);
						}
					});
				}
				
				//绑定组件的失去焦点事件.
				if($options.isOnBlurEnable != undefined && $options.isOnBlurEnable == true){
					
					$target.unbind("blur");
					
					$target.blur(function(){
						
						//自定义函数验证之前执行.
						if($options.onBlurFuncBeforeValid != undefined && $.trim($options.onBlurFuncBeforeValid) != ""){
							eval($.trim($options.onBlurFuncBeforeValid)+"()");
						}
						
						$target.dispatchJEvent($guid+"_validate_event",{"type":"submit","onBlurId":$tarId},false,true);
						
						//自定义函数验证之后执行.
						if($options.onBlurFuncAfterValid != undefined && $.trim($options.onBlurFuncAfterValid) != ""){
							eval($.trim($options.onBlurFuncAfterValid)+"("+$jqueryValidError+")");
						}
					});
				}
				else{
					//失去时焦点执行
					if(($options.onBlurFunc != undefined && $.trim($options.onBlurFunc) != "")){
						
						$target.unbind("blur");
						
						$target.blur(function(){
							eval($.trim($options.onBlurFunc)+"()");
						});
					}
				}
				
				//自定义函数获得焦点执行.
				if($options.onFocusFunc != undefined && $.trim($options.onFocusFunc) != ""){
					
					$target.unbind("focus");
					
					$target.focus(function(){
						$jqueryValidError = 0;
						eval($.trim($options.onFocusFunc)+"()");
						setCaretPosition($target.attr("id"));
					});
				}
			}
		});
		
		if(callbackFun && callbackFun.callback){
			CallBackMap[$guid+"_callback"] = callbackFun.callback;
		}
		if(callbackFun && callbackFun.resetCallBack){	//重置回调.
			CallBackMap[$guid+"_resetCallback"] = callbackFun.resetCallBack;
		}
		
		
		//派发容器提交/确定按钮事件.
		$container.find(".submitBtn").each(function(){
			var $target = $(this);
			
			$target.unbind("click");
			
			$target.click(function(){
				$jqueryValidError = 0;	//重置错误计数.				
				$jqueryValidGroupErrorArray = [];	//初始化数组
				
				$container.find("span[id$='_msg_tip']").each(function(){	//隐藏所有错误提示.
					$(this).hide();
				});
				
				$target.attr("disabled",true);	//按钮锁定.
				if(options.showFeildOnSubmit){
					$container.hide();	//隐藏容器.
				}
				if(options.showOnSubmitTip && options.showOnSubmitTip == true){
					showOnSubmitTip($guid,options.submitTipType,LOADING_IMG+" 正在执行操作，请稍后......");	//添加提交后提示.
				}
				$target.dispatchJEvent($guid+"_validate_event",{"type":"submit"},false,true);
				
				//错误计数为0则执行回调函数.
				if($jqueryValidError == 0){
					$container.find("span[id$='_msg_tip']").each(function(){	//隐藏所有正确提示.
						$(this).hide();
					});
					
					//组装参数.
					var results = {showFeild:true};
					$container.find($valideComponent).each(function(){
						var $target = $(this);
						results[$.trim($target.attr("id"))] = $target.val();
					});
					
					results["show"] = function(){
						//存在验证错误或者不存在iframe加载时执行解锁提示操作.
						if($jqueryValidError != 0 || options.iframeId == undefined || $.trim(options.iframeId) == ""){
							showAfterSubmitTip($guid,options.submitTipType);
						}
						$target.removeAttr("disabled");	//按钮锁定释放.
						if(results.showFeild){
							$container.show();	//显示容器.
						}
					};
					
					if(CallBackMap[$guid+"_callback"]){
						CallBackMap[$guid+"_callback"](results);
					}
				}
				else{
					
					//存在验证错误或者不存在iframe加载时执行解锁提示操作.
					if($jqueryValidError != 0 || options.iframeId == undefined || $.trim(options.iframeId) == ""){
						showAfterSubmitTip($guid,options.submitTipType);
					}
					$target.removeAttr("disabled");	//按钮锁定释放.
					$container.show();	//显示容器.
					return;
				}
				
				//存在验证错误或者不存在iframe加载时执行解锁提示操作.
				if(options.isLoadingColseOnHand == false){
					if($jqueryValidError != 0 || options.iframeId == undefined || $.trim(options.iframeId) == ""){
						showAfterSubmitTip($guid,options.submitTipType);
					}
					$target.removeAttr("disabled");	//按钮锁定释放.
					$container.show();	//显示容器.
				}
			});
		});
		
		//派发容器按钮重置事件.
		$container.find(".resetBtn").each(function(){
			var $target = $(this);
			
			$target.unbind("click");
			
			$target.click(function(){
				
				$jqueryValidError = 0;	//重置错误计数.
				$jqueryValidGroupErrorArray = [];	//初始化数组
				$container.find("span[id$='_msg_tip']").each(function(){	//隐藏所有错误提示.
					$(this).hide();
				});
				
				$target.attr("disabled",true);	//按钮锁定.
				$target.dispatchJEvent($guid+"_validate_event",{"type":"reset"},false,true);
				
				if(CallBackMap[$guid+"_resetCallback"]){
					CallBackMap[$guid+"_resetCallback"]();
				}
				$target.removeAttr("disabled");	//按钮锁定释放.
			});
		});
	};
	
})(jQuery);